use actix_web::{ get, HttpResponse, Responder };
use rusqlite:: Connection;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Student {
    // 姓名
    id: i32,
    name: String,
    // 年级
    rank: i8,
    class: i8,
    // 宿舍
    dormitory: i8,
    dormitory_room: i16,
    // 积分
    credits: f32
}

#[get("/student/list")]
pub async fn student_list() -> impl Responder {
    let conn = Connection::open("./data/data.db").expect("curd/student/read.rs | pub async fn /student/list() -> 数据库连接失败！");
    let mut stmt = conn.prepare("SELECT * FROM student").expect("curd/student/read.rs | pub async fn /student/list() -> 查询失败！");

    let student_iter = stmt.query_map([], |row| {
        Ok(Student {
            id: row.get(0)?,
            name: row.get(1)?,
            rank: row.get(2)?,
            class: row.get(3)?,
            dormitory: row.get(4)?,
            dormitory_room: row.get(5)?,
            credits: row.get(6)?,
        })
    }).expect("curd/student/read.rs | pub async fn /student/list() -> 迭代失败！");

    let mut student_vec = Vec::new();
    for student in student_iter {
        student_vec.push(student.unwrap());
    }

    HttpResponse::Ok().json(student_vec)
}

// 获取所有年级
#[derive(Debug, Serialize, Deserialize)]
struct Rank {
    #[allow(dead_code)]
    rank: i8
}

#[get("/student/rank")]
pub async fn rank_list() -> impl Responder {
    let conn = Connection::open("./data/data.db").expect("curd/student/read.rs | pub async fn /student/rank() -> 数据库连接失败！");
    let mut stmt = conn.prepare("SELECT DISTINCT rank FROM student").expect("curd/student/read.rss | pub async fn /student/rank() -> 查询失败！");

    let rank_iter = stmt.query_map([], |row| {
        Ok(Rank {
            rank: row.get(0)?
        })
    }).expect("curd/student/read.rs | pub async fn /student/rank() -> 迭代失败！");

    let mut rank_vec = Vec::new();
    for rank in rank_iter {
        rank_vec.push(rank.unwrap());
    }

    HttpResponse::Ok().json(rank_vec)
}

// 获取所有班级
#[derive(Debug, Serialize, Deserialize)]
struct Class {
    #[allow(dead_code)]
    class: i8
}

#[get("/student/class")]
pub async fn class_list() -> impl Responder {
    let conn = Connection::open("./data/data.db").expect("curd/student/read.rs | pub async fn /student/class() -> 数据库连接失败！");
    let mut stmt = conn.prepare("SELECT DISTINCT class FROM student").expect("curd/student/read.rss | pub async fn /student/class() -> 查询失败！");

    let class_iter = stmt.query_map([], |row| {
        Ok(Class {
            class: row.get(0)?
        })
    }).expect("curd/student/read.rs | pub async fn /student/class() -> 迭代失败！");

    let mut class_vec = Vec::new();
    for class in class_iter {
        class_vec.push(class.unwrap());
    }

    HttpResponse::Ok().json(class_vec)
}
